<?php
abstract class BaseDb {
    protected $conn;
    protected $db;
    protected $table_name;
    
    public function __construct() {
        if(empty($this->db)) {
            $db_conf = ConfLib::get('db', 'db');
            $tmp = StrLib::firstToUpper($db_conf['api']) . 'DbEngine';
            $this->db = new $tmp ();
            $this->conn = $this->db->connect($db_conf);
            $tmp = $db_conf;
            $tmp['table_name'] = $this->table_name;
            $this->sql = new SQL_Maker($db_conf['db_product'], $this->conn, $tmp);
        }
    }

    public function connect($db_conf) {
        switch($db_conf['api']) {
            case 'pdo' :
                break;
            case 'mysqli' :
                //http://www.php.net/manual/zh/mysqli.construct.php
                $this->conn = new mysqli($db_conf['host'], $db_conf['username'], $db_conf['password'], $db_conf['db_name'], $db_conf['port'], $db_conf['unix_domain_socket']); //todo persistent
                break;
            case 'pgsql' :
                //http://php.net/manual/en/function.pg-connect.php
                $host = $db_conf['host'];
                if(!empty($db_conf['unix_domain_socket'])) {
                    $host = $db_conf['unix_domain_socket'];
                }
                $this->conn = pg_connect('host=' . $host . ' port=' . $db_conf['port'] . ' dbname=' . $db_conf['db_name'] . ' user=' . $db_conf['username'] . ' password=' . $db_conf['password']);
                break;
        }
        return true;
    }

    
    public function delete($where='') {
        $sql = $this->sql->delete($where);
        return $this->db->delete($sql);
    }
    
    public abstract function insertRow($data);
    
    public abstract function insertRows($data);
    
    public function selectCount($where='') {
        $sql = $this->sql->selectCount($where);
        return $this->db->selectCount($sql);
    }
    
    public function selectRow($where='', $column='*', $limit_start=0, $group_by='', $order_by='') {
        $sql = $this->sql->select($where, $column, $limit_start, 1, $group_by, $order_by);
        return $this->db->selectRow($sql);
    }
    
    public function selectRows($where='', $column='*', $limit_start=0, $limit_size='', $group_by='', $order_by='') {
        $sql = $this->sql->select($where, $column, $limit_start, $limit_size, $group_by, $order_by);
        return $this->db->selectRows($sql);
    }
    
    public abstract function update($where='', $data);
    
    public function query($sql) {
        return $this->db->query($sql);
    }
}
?>
